package com.shallwead.bna.util.gcm;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.PowerManager;
import android.util.Log;

import com.shallwead.bna.BnA;
import com.shallwead.bna.object.AdGcmMsg;
import com.shallwead.bna.object.GCM;
import com.shallwead.bna.util.Logger;
import com.shallwead.bna.util.SharedPreferenceUtil;

public class GCM_IntentService extends IntentService {

	public GCM_IntentService() {
		super("GCM_IntentService");
	}

	private static PowerManager.WakeLock sWakeLock;
	private static final Object LOCK = GCM_IntentService.class;
	private static Context mContext;

	static void runIntentInService(Context context, Intent intent) {
		mContext = context;
		BnA bna = new BnA(mContext);
		synchronized (LOCK) {
			if (sWakeLock == null) {
				PowerManager pm = (PowerManager) context
						.getSystemService(Context.POWER_SERVICE);
				sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
						"my_wakelock");
			}
		}
		sWakeLock.acquire();
		intent.setClassName(context, GCM_IntentService.class.getName());
		context.startService(intent);
	}

	@Override
	public final void onHandleIntent(Intent intent) {
		try {
			String action = intent.getAction();
			if (action.equals("com.google.android.c2dm.intent.REGISTRATION")) {

				Log.e("TAG", action);
				handleRegistration(intent);

			} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {

				Log.e("TAG", action);
				handleMessage(intent);

			}
		} finally {
			synchronized (LOCK) {
				sWakeLock.release();
			}
		}
	}

	private String registrationId = null;

	private void handleRegistration(Intent intent) {

		registrationId = intent.getStringExtra("registration_id");
		String error = intent.getStringExtra("error");
		String unregistered = intent.getStringExtra("unregistered");
		// registration succeeded

		if (registrationId != null) {
			Log.e("TAG", registrationId);
			boolean isGCM = SharedPreferenceUtil.getbooleanSharedPreference(
					mContext.getApplicationContext(), "isGCM");
			GCM g = new GCM(mContext, registrationId);
			if (!isGCM) {
				new RegisterDevice().execute(g);
			}
		}

		// unregistration succeeded
		if (unregistered != null) {
			// get old registration ID from shared preferences
			// notify 3rd-party server about the unregistered ID
		}

		// last operation (registration or unregistration) returned an error;
		if (error != null) {
			if ("SERVICE_NOT_AVAILABLE".equals(error)) {
				// optionally retry using exponential back-off
				// (see Advanced Topics)
			} else {
				// Unrecoverable error, log it
				Log.i("GCM", "Received error: " + error);
			}
		}
	}

	// private String BinaUrl = Util.base_Url + Util.register_Device;

	private void handleMessage(Intent intent) {

		AdGcmMsg gcmMsg = null;
		try {
			gcmMsg = new AdGcmMsg(intent.getStringExtra("pushIDX"),
					intent.getStringExtra("title"),
					intent.getStringExtra("content"),
					intent.getStringExtra("imageUrl"),
					intent.getStringExtra("notiType"),
					intent.getStringExtra("linkType"),
					intent.getStringExtra("url"), intent.getStringExtra("des"),
					intent.getStringExtra("pkg"));
		} catch (NullPointerException e) {
			GCM_IntentService.this.stopSelf();
		}

		if (BnA.TestMode) {
			if (gcmMsg != null) {
				Logger.e(gcmMsg.toString());
				BnA bna = new BnA(mContext);
				BnA.gcmMsg = gcmMsg;
				if (!BnA.isInstall(mContext, gcmMsg.getPkg()))
					GCM_Utils.setNotiType(mContext, gcmMsg);
			}
		} else {
			if (gcmMsg != null && !"0".equals(gcmMsg.getPushIDX())) {
				Logger.e(gcmMsg.toString());
				BnA bna = new BnA(mContext);
				BnA.gcmMsg = gcmMsg;
				if (!BnA.isInstall(mContext, gcmMsg.getPkg()))
					GCM_Utils.setNotiType(mContext, gcmMsg);
			}
		}

	}

	class RegisterDevice extends AsyncTask<GCM, Void, Boolean> {

		@Override
		protected Boolean doInBackground(GCM... params) {

			GCM_Utils.RegisterDevice(mContext, params[0]);

			return true;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
		}

	}

}
